<!-- 账号密码登录表单 -->
<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus';
import type { LoginDTO } from '@/api/auth/types';
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { login } from '@/api';
import { useAppStore, useUserStore } from '@/stores';
import { useSessionStore } from '@/stores/modules/session';
import { guestService } from '@/services/guestService';

import { getUuid } from '@/utils/utils';

const userStore = useUserStore();
const appStore = useAppStore();
const sessionStore = useSessionStore();

const formRef = ref<FormInstance>();
const loading = ref(false);

const formModel = reactive<LoginDTO>({
  username: '',
  password: '',
});

const rules = reactive<FormRules<LoginDTO>>({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
});

const router = useRouter();
async function handleSubmit() {
  if (loading.value)
    return;

  try {
    loading.value = true;
    await formRef.value?.validate();
    const res = await login({ ...formModel, uuid: getUuid() });
    if (res.code !== 0)
      return ElMessage.error(res.msg);
    // 用户主动登录，清除游客状态
    guestService.onUserLogin();
    
    // 设置 token 和用户信息
    res.data.token && userStore.setToken(res.data.token);
    // res.data.userInfo && userStore.setUserInfo(res.data.userInfo);

    // 初始化应用数据
    const initSuccess = await appStore.initApp();
    if (!initSuccess) {
      ElMessage.error('初始化应用数据失败');
      return;
    }

    ElMessage.success('登录成功');
    userStore.closeLoginDialog();

    // 立刻获取会话列表
    await sessionStore.requestSessionList(1, true);
    router.replace('/');
  }
  catch (error: any) {
    console.error('登录错误:', error);

    // 优先显示服务端返回的错误信息
    let errorMessage = '登录失败，请稍后重试';

    if (error?.result?.msg) {
      // 如果有服务端返回的错误信息，优先使用
      errorMessage = error.result.msg;
    }
    else if (error?.response?.statusText) {
      // 如果没有具体错误信息，使用HTTP状态文本
      errorMessage = error.response.statusText;
    }
    else if (error?.message) {
      // 最后使用通用错误信息
      errorMessage = error.message;
    }

    ElMessage.error(errorMessage);
  }
  finally {
    loading.value = false;
  }
}
</script>

<template>
  <div class="custom-form">
    <el-form ref="formRef" :model="formModel" :rules="rules" style="width: 230px" @submit.prevent="handleSubmit">
      <el-form-item prop="username">
        <el-input v-model="formModel.username" placeholder="请输入用户名">
          <template #prefix>
            <el-icon>
              <User />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="formModel.password" placeholder="请输入密码" type="password" show-password>
          <template #prefix>
            <el-icon>
              <Lock />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="width: 100%" native-type="submit" :loading="loading" :disabled="loading">
          {{ loading ? '登录中...' : '登录' }}
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 注册登录 -->
    <!-- <div class="form-tip font-size-12px flex items-center">
      <span>没有账号？</span>
      <span
        class="c-[var(--el-color-primar,#409eff)] cursor-pointer"
        @click="loginFromStore.setLoginFormType('RegistrationForm')"
      >
        立即注册
      </span>
    </div> -->
  </div>
</template>

<style scoped lang="scss">
.custom-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.form-group {
  display: flex;
  gap: 8px;
  align-items: center;
}
.login-btn {
  padding: 12px;
  margin-top: 24px;
  color: white;
  cursor: pointer;
  background: #409eff;
  border: none;
  border-radius: 4px;
}
</style>
